<template>
    <div>
        <!--        <el-row>-->
        <!--            <el-col :span="24">-->
        <el-card class="role-access-card">
            <el-form ref="form" :rules="rules" :model="form" inline>
                <el-form-item label="方案名称" prop="name">
                    <el-input v-model="form.name" placeholder="方案名称" style="width: 200px;"></el-input>

                    <destroy-confirm
                        v-if="form.id > 0"
                        route="appSourceConfig/Destroy"
                        :primary="form.id"
                        @success="onDelete">
                    </destroy-confirm>
                </el-form-item>

                <!--<el-divider>充值相关</el-divider>-->
                <el-divider content-position="left">基础配置</el-divider>
                <el-row type="flex" style="flex-wrap:wrap">
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="商城点券">
                            <select-mall v-model="form.configs.mall_id" :form="true" :clearable="false"></select-mall>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="商城奶酪">
                            <select-mall-exchange v-model="form.configs.mall_exchange_id" :form="true" :clearable="false"></select-mall-exchange>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="商城市场">
                            <select-mall-market v-model="form.configs.mall_market_id" :form="true" :clearable="false"></select-mall-market>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="商城换购返利">
                            <select-mall-market-rebate v-model="form.configs.mall_market_rebate_id" :form="true" :clearable="false"></select-mall-market-rebate>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="商城特惠礼包">
                            <select-mall-special v-model="form.configs.mall_special_id" :form="true" :clearable="false"></select-mall-special>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6" v-for="(item, index) in activityMgrGroupByType" :key="'activity' + index">
                        <el-form-item :label="item.name">
                            <el-select
                                v-if="isMultiActivityType(index)"
                                v-model="activitySelects[index]"
                                multiple
                                collapse-tags
                                class="filter-item"
                                placeholder="请选择"
                                clearable
                                style="width: 100%;">
                                <el-option
                                    v-for="(item1, index) in item.items"
                                    :key="index"
                                    :label="item1.id + ' ) ' + item1.name"
                                    :value="item1.id">
                                </el-option>
                            </el-select>
                            <el-select
                                v-else
                                v-model="activitySelects[index]"
                                class="filter-item"
                                placeholder="请选择"
                                clearable
                                style="width: 100%;">
                                <el-option
                                    v-for="(item1, index) in item.items"
                                    :key="index"
                                    :label="item1.id + ' ) ' + item1.name"
                                    :value="item1.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="新手策略">
                            <select-newuser-protect v-model="form.configs.newuser_protect_id" :form="true" :clearable="false"></select-newuser-protect>
                        </el-form-item>
                    </el-col>
                    <!--                            <el-col :span="24" :md="12" :lg="6">-->
                    <!--                                <el-form-item label="新手充值策略">-->
                    <!--                                    <select-newuser-pay-protect v-model="form.configs.newuser_pay_protect_id" :form="true" :clearable="false"></select-newuser-pay-protect>-->
                    <!--                                </el-form-item>-->
                    <!--                            </el-col>-->
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="权益策略">
                            <select-withdraw-limit v-model="form.configs.withdraw_limit_id" :form="true" :clearable="false"></select-withdraw-limit>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="充值限额策略">
                            <select-pay-limit v-model="form.configs.pay_limit_id" :form="true" :clearable="false"></select-pay-limit>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="充值限额">
                            <el-input-number v-model="form.configs.paylimit" placeholder=""/> 元
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="点券限额">
                            <el-input-number v-model="form.configs.costlimit" placeholder=""/>
                        </el-form-item>
                    </el-col>
                    <!--                            <el-col :span="24" :md="12" :lg="6">-->
                    <!--                                <el-form-item label="VIP配置">-->
                    <!--                                    <select-easy-config v-model="form.configs.vip_config_id" :type="'vip_config'" :form="true" :clearable="false"></select-easy-config>-->
                    <!--                                </el-form-item>-->
                    <!--                            </el-col>-->
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="新充值Buff">
                            <select-pay-buff-upgrade v-model="form.configs.pay_buff_upgrade_id" :form="true" :clearable="false"></select-pay-buff-upgrade>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" :md="12" :lg="6">
                        <el-form-item label="引导类型">
                            <el-radio-group v-model="form.configs.guide_type_id">
                                <el-radio-button :label="item.value" v-for="(item, index) in options.guideType" :key="index">{{ item.label }}</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-divider content-position="left">场次安排</el-divider>

                <el-row>
                    <el-col :span="24" class="pl-5 pr-5">
                        <el-col :span="24" :md="12" :lg="6">
                            <el-form-item label="棒棒糖场">
                                <select-scene v-model="form.configs.scene_id_type_1" :type="1" :multiple="true" :clearable="false"></select-scene>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" :md="12" :lg="6">
                            <el-form-item label="J场">
                                <select-scene v-model="form.configs.scene_id_type_2" :type="2" :multiple="true" :clearable="false"></select-scene>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" :md="12" :lg="6">
                            <el-form-item label="数值场">
                                <select-scene v-model="form.configs.scene_id_type_3" :type="3" :multiple="true" :clearable="false"></select-scene>
                            </el-form-item>
                        </el-col>
                    </el-col>
                </el-row>

                <el-divider content-position="left"><b class="color-danger">隐藏</b>客户端功能</el-divider>

                <!--                        <el-row>-->
                <!--                            <el-col>-->
                <el-form-item label="">
                    <!--                                    <template #label>-->
                    <!--                                        <b class="color-danger">隐藏</b>客户端功能-->
                    <!--                                    </template>-->
                    <!--                                    <select-config-build v-model="form.configs.ban_function_ids"/>-->
                    <checkbox-config-build v-model="form.configs.ban_function_ids"/>
                    <span style="font-size: 13px;">数据维护: 快速配置中 build.json</span>
                </el-form-item>
                <!--                            </el-col>-->
                <!--                        </el-row>-->

                <el-divider content-position="left">注册赠送</el-divider>
                <!--                        <el-row>-->
                <!--                            <el-col>-->
                <el-form-item>
                    <h6>
                        <el-button icon="el-icon-plus" type="primary" plain @click="addNewPlayerGift">
                            添加赠送物品
                        </el-button>
                    </h6>
                    <el-table :data="form.configs.new_player_give_away.items" style="width: 600px">
                        <el-table-column property="id" label="物品">
                            <template slot-scope="scope">
                                <select-item v-model="scope.row.id" @input="syncItemType(scope.$index, scope.row.id)"></select-item>
                            </template>
                        </el-table-column>
                        <el-table-column property="type" label="类型">
                            <template slot-scope="scope">
                                {{ scope.row.type ? itemOptions.type[scope.row.type].label : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column property="num" label="数量">
                            <template slot-scope="scope">
                                <el-input-number v-model="scope.row.num" placeholder="数量"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80">
                            <template slot-scope="scope">
                                <el-button type="danger" @click="deleteNewPlayerGift(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!--                            </el-col>-->
                <!--                        </el-row>-->

                <el-divider content-position="left">其他开关</el-divider>
                <!--                        <el-row>-->
                <!--                            <el-col :span="24" :md="12" :lg="6">-->
                <!--                                <el-form-item label="支付宝通道">-->
                <!--                                    <el-radio-group v-model="form.configs.pay_channel_alipay">-->
                <!--                                        <el-radio-button :label="item.value" v-for="(item, index) in options.payChannelAlipays" :key="index" :disabled="item.disabled">{{ item.label }}</el-radio-button>-->
                <!--                                    </el-radio-group>-->
                <!--                                </el-form-item>-->
                <!--                            </el-col>-->
                <!--                            <el-col :span="24" :md="12" :lg="6">-->
                <!--                                <el-form-item label="微信通道">-->
                <!--                                    <el-radio-group v-model="form.configs.pay_channel_wechat">-->
                <!--                                        <el-radio-button :label="item.value" v-for="(item, index) in options.payChannelWechats" :key="index" :disabled="item.disabled">{{ item.label }}</el-radio-button>-->
                <!--                                    </el-radio-group>-->
                <!--                                </el-form-item>-->
                <!--                            </el-col>-->
                <!--                            <el-col>-->
                <el-form inline label-position="top">
                    <el-form-item label="新手引导">
                        <switch-radio v-model="form.configs.newuser_guide_enabled" :values="[false, true]"></switch-radio>
                    </el-form-item>
                    <el-form-item label="CDKEY">
                        <switch-radio v-model="form.configs.cdk" :values="[false, true]"></switch-radio>
                    </el-form-item>
                    <!--                                    <el-form-item label="你好支付宝">-->
                    <!--                                        <switch-radio v-model="form.configs.nhpay_zfb_enabled" :values="[false, true]"></switch-radio>-->
                    <!--                                    </el-form-item>-->
                    <!--                                    <el-form-item label="你好微信">-->
                    <!--                                        <switch-radio v-model="form.configs.nhpay_wx_enabled" :values="[false, true]"></switch-radio>-->
                    <!--                                    </el-form-item>-->
                    <el-form-item label="三方商城SDK">
                        <switch-radio v-model="form.configs.third_exchange_enabled" :values="[false, true]"></switch-radio>
                    </el-form-item>
                </el-form>
                <!--                            </el-col>-->
                <!--                        </el-row>-->
                <el-divider></el-divider>

                <el-row v-if="form.configs.third_exchange_enabled">
                    <el-col :span="24" class="pl-5 pr-5">
                        <el-col :span="24" :md="12" :lg="6">
                            <el-form-item label="三方商城APPID">
                                <select-third-exchange-config v-model="form.configs.third_exchange_id"/>
                            </el-form-item>
                        </el-col>
                    </el-col>
                </el-row>
                <el-divider v-if="form.configs.third_exchange_enabled"></el-divider>

                <el-form-item label=" ">
                    <el-button type="primary" :loading="loading" @click="submit">确定</el-button>
                    <el-button @click="cancel">返回</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!--            </el-col>-->
        <!--        </el-row>-->

        <!--        <el-row>-->
        <!--            <el-col>-->
        <h3>当前方案生效渠道</h3>
        <el-card class="role-access-card" v-for="(typeItem, typeIndex) in appSourceOptions.type" :key="typeIndex" v-if="appSourceGroupByType[typeIndex]">
            <div slot="header" class="clearfix">
                <el-checkbox
                    v-model="selectedAll[typeIndex]"
                    @change="handleCheckAllChange($event, typeIndex)"
                    :indeterminate="isIndeterminate[typeIndex]">
                    {{ typeItem.label }}
                </el-checkbox>
            </div>

            <template>
                <el-checkbox-group v-model="form.sources">
                    <el-checkbox
                        @change="handleCheckedChange($event, typeIndex)"
                        v-for="(item, index) in appSourceGroupByType[typeIndex]"
                        :label="item.id"
                        :key="index">
                        {{ item.id }} ) {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </template>
        </el-card>
        <!--            </el-col>-->
        <!--        </el-row>-->
    </div>
</template>

<script>
import SelectScene from '~/components/Select/scene'
import SelectActivityMgr from '~/components/Select/activity-mgr'
import SelectMall from '~/components/Select/mall'
import SelectMallExchange from '~/components/Select/mall-exchange'
import SelectMallWithdraw from '~/components/Select/mall-withdraw'
import SelectMallMarket from '~/components/Select/mall-market'
import SelectMallMarketRebate from '~/components/Select/mall-market-rebate'
import SelectMallSpecial from '~/components/Select/mall-special'
import SelectNewuserProtect from '~/components/Select/newuser-protect'
import SelectNewuserPayProtect from '~/components/Select/newuser-pay-protect'
import SelectWithdrawLimit from '~/components/Select/withdraw-limit'
import SelectPayLimit from '~/components/Select/pay-limit'
import SelectEasyConfig from '~/components/Select/easy-config'
import SelectPayBuffUpgrade from '~/components/Select/pay-buff-upgrade'
import SwitchRadio from '~/components/Switch/radio';
import CheckboxConfigBuild from '~/components/Checkbox/config-build';
import SelectThirdExchangeConfig from '~/components/Select/third-exchange-config.vue';

export default {
    props: {
        data: {

        }
    },
    components: {
        SelectScene,
        SelectMall,
        SelectMallExchange,
        SelectMallMarket,
        SelectMallMarketRebate,
        SelectMallSpecial,
        SelectActivityMgr,
        SelectMallWithdraw,
        SelectNewuserProtect,
        SelectNewuserPayProtect,
        SelectWithdrawLimit,
        SelectPayLimit,
        SelectEasyConfig,
        SelectPayBuffUpgrade,
        SwitchRadio,
        CheckboxConfigBuild,
        SelectThirdExchangeConfig,
    },
    data() {
        return {
            loading: false,
            form: {},
            formDefault: {
                id: 0,
                name: '',
                configs: {
                    paylimit: 0,
                    costlimit: 0,
                    guide_type_id: 0,
                    nhpay_zfb_enabled: false,
                    nhpay_wx_enabled: false,
                    pay_channel_alipay: '',
                    pay_channel_wechat: '',
                    cdk: false,
                    newuser_guide_enabled: false,
                    ban_function_ids: [],
                    new_player_give_away: {items: []},
                    third_exchange_id: '',
                    third_exchange_enabled: false,
                },
                sources: [],
            },
            rules: {
                name: { required: true, message: '请输入名称', trigger: 'blur', },
            },
            options: this.$store.state.appSourceConfig.options,
            itemOptions: this.$store.state.item.options,
            appSourceOptions: this.$store.state.appSource.options,
            selectedAll: {},
            isIndeterminate: {},
            activitySelects: {},
            // 需要多选的活动类型 月卡
            multiActivityTypes: ['1-6'],
            // 新手赠礼
            new_player_gift: {
                id: '',
                type: '',
                des: '',
                num: 0,
            }
        }
    },
    computed: {
        appSources () {
            return this.$store.state.appSource.all;
        },
        appSourceGroupByType() {
            // 将渠道按类型分组
            let groups = {};
            this.$store.state.appSource.all.map(v => {
                if (!groups[v.type]) {
                    groups[v.type] = [v];
                } else {
                    groups[v.type].push(v);
                }
            });
            return groups;
        },
        activityMgrs() {
            // 只看显示
            return this.$store.state.activityMgr.all.filter(v => v.display);
        },
        activityMgrGroupByType() {
            // 按活动类型+客户端类型分组, 方便直接输出 name 和 select
            let groups = {};
            let options = this.$store.state.activityMgr.options;
            this.activityMgrs.map(v => {
                let type = v.activity_type +'-'+ v.client_type;
                let name = (options.activity_type[v.activity_type] ? options.activity_type[v.activity_type].label : v.activity_type)
                    + ' - '
                    + (options.client_type[v.client_type] ? options.client_type[v.client_type].label : v.client_type);

                if (!groups[type]) {
                    groups[type] = {
                        name: name,
                        items: [],
                    };
                }
                groups[type].items.push(v);
            });
            return groups;
        },
        items() {
            return this.$store.state.item.all;
        },
        itemsObj() {
            let obj = {};
            this.items.map(v => {
                v.type_name = this.itemOptions.type[v.type];
                obj[v.id] = v;
            })
            return obj;
        },
    },
    watch: {
        data (newVal) {
            this.syncForm();
        },
        activityMgrGroupByType() {
            this.syncActivitySelects();
        },
    },
    methods: {
        getFormAction() {
            return this.form.id ? 'appSourceConfig/Update' : 'appSourceConfig/Store';
        },
        submit() {
            this.$refs.form.validate(valid => {
                if (!valid) return false;
                // 简单校验
                let form = this.handleForm();
                if (form.configs.third_exchange_enabled) {
                    if (!this.form.configs.third_exchange_id) {
                        this.$message.warning("开启三方商城SDK后, 需要选择三方商城APPID");
                        return false;
                    }
                }
                this.loading = true;
                this.$store.dispatch(this.getFormAction(), form).then(res => {
                    this.$message.success(res.data.message);
                    // 更新缓存
                    this.$store.dispatch('appSourceConfig/All', 'appSourceConfig');
                    this.$emit('submit');
                }).finally(() => {
                    this.loading = false;
                });
            });
        },
        handleForm() {
            // 处理form.activity_mgr_id
            let form = this.$helper.deepClone(this.form);
            let activity_mgr_id = [];
            for (let i in this.activitySelects) {
                if (this.isMultiActivityType(i)) {
                    if (this.activitySelects[i].length) activity_mgr_id.push(...this.activitySelects[i]);
                } else {
                    if (this.activitySelects[i]) activity_mgr_id.push(this.activitySelects[i]);
                }
            }
            form.configs.activity_mgr_id = activity_mgr_id;
            form.configs.paylimit *= 100; // 转成分
            // 注册赠送, 只要正整数
            form.configs.new_player_give_away.items.map(v => {
                if (v.num < 0) {
                    v.num = 0
                }
                v.num = parseInt(v.num);
                v.type = parseInt(v.type);
            });
            return form;
        },
        cancel() {
            this.$emit('cancel');
        },
        onDelete() {
            this.$emit('delete');
        },
        syncForm() {
            let tmpData = this.$helper.deepClone(Object.assign({}, this.formDefault, this.data));

            // 如果没有新手赠礼或者新手赠礼不是数组(老的数据), 则进行初始化
            if (!tmpData.configs.new_player_give_away.items  || !Array.isArray(tmpData.configs.new_player_give_away.items)) {
                tmpData.configs.new_player_give_away = this.$helper.deepClone(this.formDefault.configs.new_player_give_away);
            }

            if (!isNaN(Number(tmpData.configs.paylimit))) tmpData.configs.paylimit /= 100; // 转成元

            this.form = tmpData;

            // 渠道默认选中
            Object.keys(this.appSourceOptions.type).map(k => {
                this.handleCheckedChange(true, k);
            });
            this.syncActivitySelects();
        },
        syncActivitySelects() {
            // 同步状态
            for (let type in this.activityMgrGroupByType) {
                // 全部清空
                if (this.isMultiActivityType(type)) {
                    this.$set(this.activitySelects, type, []);
                } else {
                    this.$set(this.activitySelects, type, '');
                }

                let items = this.activityMgrGroupByType[type].items;
                for (let i in items) {
                    if (this.form.configs.activity_mgr_id && this.form.configs.activity_mgr_id.includes(items[i].id)) {
                        if (this.isMultiActivityType(type)) {
                            this.activitySelects[type].push(items[i].id);
                        } else {
                            this.$set(this.activitySelects, type, items[i].id)
                        }
                    }
                }
            }
        },
        // 顶级权限选中|取消, 自动选中|取消子级权限
        handleCheckAllChange(val, pKey) {
            this.isIndeterminate[pKey] = false;
            let typeItem = this.appSourceOptions.type[pKey];
            if (val) {
                this.appSources.map(v => {
                    if (typeItem.value === v.type && this.form.sources.indexOf(v.id) === -1) this.form.sources.push(v.id);
                });
            } else {
                this.appSources.map(v => {
                    if (typeItem.value === v.type && this.form.sources.indexOf(v.id) > -1)this.form.sources.splice(this.form.sources.indexOf(v.id), 1);
                });
            }
        },
        // 子级选中|取消, 检查顶级权限是否需要选中|取消
        handleCheckedChange(val, pKey) {
            let typeItem = this.appSourceOptions.type[pKey];
            let childArr = this.appSources.filter(v => { return v.type === typeItem.value; }).map(v => v.id);
            let checkedLength = this.form.sources.filter(v => childArr.includes(v)).length;
            this.isIndeterminate[pKey] = checkedLength > 0 && checkedLength < childArr.length;
            this.selectedAll[pKey] = childArr.length && checkedLength === childArr.length;
        },
        getAppSources() {
            if (this.appSources.length === 0) this.$store.dispatch('appSource/All', 'appSource');
        },
        getActivityMgrs() {
            if (!this.activityMgrs.length) this.$store.dispatch('activityMgr/All', 'activityMgr');
        },
        // 是否是多选的活动类型
        isMultiActivityType(type) {
            return this.multiActivityTypes.includes(type);
        },
        syncItemType(index, id) {
            if (this.$helper.isEmptyObj(this.itemsObj)) return;
            let item = this.itemsObj[id];
            this.form.configs.new_player_give_away.items[index].type = item.type;
            this.form.configs.new_player_give_away.items[index].des = item.des;
        },
        addNewPlayerGift() {
            this.form.configs.new_player_give_away.items.push(this.$helper.deepClone(this.new_player_gift));
        },
        deleteNewPlayerGift(index) {
            this.form.configs.new_player_give_away.items.splice(index, 1);
        },
    },
    created () {
        this.syncForm();
        this.getAppSources();
        this.getActivityMgrs();
    }
}
</script>

<style lang="scss" scoped>
.item-row {
    margin: 0 0 10px 0;
}

.role-access-card {
    margin: 0 0 10px 0;
    .el-card__header,.el-card__body {
        line-height: 19px;
    }
    .el-card__body:empty {
        padding: 0;
    }
}
</style>

